package com.aerotechnic.dao.implementation;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import sun.reflect.generics.repository.GenericDeclRepository;

import com.aerotechnic.dao.interfaces.UserDaoIn;
import com.aerotechnic.entities.User;

@Repository
public class UserDao implements UserDaoIn {

	@Autowired
	private SessionFactory sessionFactory;

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(User t) {
		// TODO Auto-generated method stub

		getCurrentSession().save(t);

	}

	@Override
	public void delete(int id) {
		// TODO Auto-generated method stub

		User e = findByID(id);
		if (e != null)
			getCurrentSession().delete(e);

	}

	@Override
	public User findByID(int id) {
		// TODO Auto-generated method stub

		Session session = sessionFactory.getCurrentSession();

		return (User) session.createQuery("FROM User where id= " + id).list()
				.get(0);
	}

	@Override
	public void update(User t) {
		// TODO Auto-generated method stub

		getCurrentSession().update(t);

	}

	public List<User> findAll() {
		// TODO Auto-generated method stub

		return getCurrentSession().createQuery("from User").list();
	}

	public User authenticate(String login, String password) {

		List fetchedUsers = getCurrentSession().createQuery(
				"from User where login ='" + login + "' and password ='"
						+ password + "'").list();
		return fetchedUsers.isEmpty() ? null : (User) fetchedUsers.get(0);

	}

	@Override
	public int countAllUsers() {
		// TODO Auto-generated method stub
		List allUsers = getCurrentSession().createQuery("from User ").list();
		return allUsers == null ? 0 : allUsers.size();
	}

	@Override
	public List<User> find(int startIndex, int pageSize) {
		// TODO Auto-generated method stub
		List<User> allUsers = getCurrentSession().createQuery("from User")
				.setFirstResult(startIndex).setMaxResults(pageSize).list();
		return allUsers;
     
	}

}
